<template>
  <div>
    <EditTaskItemDialog ref="editTaskItemDialog"
                        @insertTaskItem="insertTaskItemCommit"
                        :auditLevel="auditLevel"
                        :knowledgeLibId="knowledgeLibId"/>
    <PreviewDialog :calculatorSore="calculatorSore" :describeContent="describeContent"
                   :fields="fields"
                   :medicalCalculatorData="medicalCalculatorData"
                   :type="cntFormulaType"
                   ref="preview"/>

    <SolveNameSuggestionDialog
      :visible.sync="nameSuggestionDialogVisible"
      :auditLevel="auditLevel"
      :status="cntTaskItem.status"
      :nameSuggestion="cntTaskItem.nameSuggestion"
      :name="cntTaskItem.name"
      @confirm="solveNameSuggestionConfirm"
      @refuse="rejectTaskItemName"/>
    <el-row>
      <el-table highlight-current-row id='taskItemTable'
                :data="taskItemList.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                :height="tableHeight"
                border
                stripe>
        <el-table-column
            label="序号"
            type="index"
            align="center"
            width="50">
        </el-table-column>
        <el-table-column prop="name" :show-overflow-tooltip="true"
                         label="子任务名称"
                         min-width="100">
          <template slot-scope="scope">
            <div v-if="UTIL.hasUnconfirmedNameSuggestion(scope.row.nameSuggestion)">
              <div style="color: red" v-html="scope.row.name"></div>
              <div>
                <el-link type="primary" @click.prevent="solveNameSuggestion(scope.row)">修改</el-link>
              </div>
            </div>
            <div v-else v-html="scope.row.name"/>
          </template>
        </el-table-column>
        <el-table-column prop="type"
                         label="类型"
                         min-width="100">
          <template slot-scope="scope">
            <span v-text="CONST.TASK_ITEM_VO[scope.row.type]">非自建</span>
          </template>
        </el-table-column>
        <el-table-column prop="status"
                         label="状态"
                         min-width="100">
          <template slot-scope="scope">
            <span>{{ getStatusName(scope) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="editor" :show-overflow-tooltip="true"
                         label="编辑"
                         min-width="100">
          <template slot-scope="scope">
            <span>{{getEditorName(scope)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="wordsCount"
                         label="完成字数"
                         min-width="100">
        </el-table-column>
        <el-table-column prop="firstAuditor" :show-overflow-tooltip="true"
                         label="初审编辑"
                         min-width="100">
          <template slot-scope="scope">
            <span>{{getFirstAuditorName(scope)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="secondAuditor" :show-overflow-tooltip="true"
                         label="复审编辑"
                         min-width="100" v-if="auditLevel > 1">

          <template slot-scope="scope">
            <span>{{getSecondAuditorName(scope)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="thirdAuditor" :show-overflow-tooltip="true"
                         label="终审编辑"
                         min-width="100" v-if="auditLevel > 2">
          <template slot-scope="scope">
            <span>{{getThirdAuditorName(scope)}}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="knowledgeLibId===CONST.QUESTION_AN_LIB_ID" :show-overflow-tooltip="true" label="关联疾病"
                         min-width="100"
                         prop="relationDisease">
        </el-table-column>
        <el-table-column prop="remark" :show-overflow-tooltip="true"
                         label="备注"
                         min-width="100">
        </el-table-column>
        <el-table-column label="操作"
                         width="200">
          <template slot-scope="scope">
            <span><el-link @click.prevent="editTaskItem(scope.row)">修改</el-link></span>
            <span v-if="scope.row.status !== 8"><el-link type="danger"
                                                         @click.prevent="deleteTaskItem(scope.row)">删除</el-link></span>
            <span><el-link @click.prevent="detailById(scope.row.knowledgeId, scope.row.status)"
                           type="primary">查看</el-link></span>
            <span><el-link @click.prevent="pressTaskItem(scope.row.id)" type="danger"
                           v-if="scope.row.status !== 8 && UTIL.isNotEmpty(scope.row.id)">催办</el-link></span>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-pagination
          :page-size.sync="pageSize"
          :page-sizes="[5, 10, 15, 20, 50, 100]"
          @size-change="handleSizeChange"
          :current-page.sync="currentPage"
          :total="taskItemList.length"
          background
          layout="total, sizes, prev, pager, next, jumper"
          style="text-align: right;margin-top: 10px"></el-pagination>
    </el-row>
  </div>
</template>

<script>
import EditTaskItemDialog from "./EditTaskItemDialog";
import PreviewDialog from "../calculator/exportModel/PreviewDialog";
import SolveNameSuggestionDialog from "./SolveNameSuggestionDialog";

export default {
  name: "TaskItemTable",
  components: {
    SolveNameSuggestionDialog,
    EditTaskItemDialog,
    PreviewDialog,
  },
  props: ['taskItemList', 'auditLevel', 'knowledgeLibId', 'systemType', 'height'],
  data() {
    return {
      knowledgeId: '',
      knowledgeStatus: '',
      currentPage: 1,
      tableHeight: 0,
      previewDialogVisible: false,
      medicalCalculatorData: [],
      calculatorSore: [],
      describeContent: '',
      fields: [],
      cntFormulaType: 1,
      pageSize: 5,
      cntTaskItem: {},
      nameSuggestionDialogVisible: false,
    }
  },
  computed: {
    editorList() {
      return this.$store.state.userList
    },
    auditorList() {
      return this.$store.state.userList
    },
  },
  methods: {
    solveNameSuggestion(taskItem){
      this.nameSuggestionDialogVisible = true
      this.cntTaskItem = taskItem;
    },
    solveNameSuggestionConfirm(nameSuggestion, name){
      let taskItemBak = JSON.parse(JSON.stringify(this.cntTaskItem))
      taskItemBak.name = name
      taskItemBak.nameSuggestion = nameSuggestion
      let param = new URLSearchParams()
      param.append("taskItem", JSON.stringify(taskItemBak))
      this.axios.post('/pmph/action/task/saveTaskItem', param)
        .then(() => {
          this.cntTaskItem.name = name
          this.cntTaskItem.nameSuggestion = nameSuggestion
          this.nameSuggestionDialogVisible = false
        })
    },
    rejectTaskItemName(nameSuggestion){
      this.nameSuggestionDialogVisible = false
      let taskItemBak = JSON.parse(JSON.stringify(this.cntTaskItem))
      taskItemBak.nameSuggestion = nameSuggestion
      let param = new URLSearchParams()
      param.append("taskItem", JSON.stringify(taskItemBak))
      this.axios.post('/pmph/action/task/saveTaskItem', param)
        .then(() => {
          this.cntTaskItem.nameSuggestion = nameSuggestion
        })
    },
    insertTaskItemCommit(taskItem) {
      this.$emit('insertTaskItem', taskItem)
    },
    insertTaskItem(taskItem) {
      this.$refs.editTaskItemDialog.title = '新增子任务'
      this.$refs.editTaskItemDialog.taskItem = taskItem
      this.$refs.editTaskItemDialog.visible = true
    },
    editTaskItem(taskItem) {
      this.$refs.editTaskItemDialog.title = '修改子任务'
      this.$refs.editTaskItemDialog.taskItem = taskItem
      this.$refs.editTaskItemDialog.visible = true
    },
    deleteTaskItem(taskItem) {
      let that = this;
      // 后台需要根据该字段判断删除的是知识表,医学计算器表,还是流程图
      taskItem.systemType = this.systemType;
      this.axios.get("/pmph/action/knowledgeLib/selectBindingKnowledge", {
        params: {
          knowledgeId: taskItem.knowledgeId
        }
      }).then((res) => {
        // bindingKnowledgeArray = [{knowledgeFieldId: "", knowledgeFieldName: "", knowledgeId: "", knowledgeName: "", knowledgeLibId: "", knowledgeLibName: ""}]
        let bindingKnowledgeArray = res.data
        if (bindingKnowledgeArray.length === 0) {
          let tip = '';
          if (CONST.TASK_ITEM.TYPE_TASK_EDITOR_CREATE === taskItem.type || CONST.TASK_ITEM.TYPE_TASK_EDITOR_CREATE_KNOWLEDGE_UNIT === taskItem.type) {
            tip = '您确定要删除该子任务吗，删除后对应的已经编辑的内容都将一并被删除';
          } else if (CONST.TASK_ITEM.TYPE_KNOWLEDGE_EDITOR_CREATE === taskItem.type) {
            tip = '您确定要删除该子任务吗，该任务为编辑自建任务，删除后对应的已经编辑的内容都将一并被删除';
          } else {
            tip = '您确定要删除该修订子任务，相应的已经修订的内容将同步被删除';
          }
          this.$confirm(tip, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            callback: function (action) {
              if (action === 'confirm') {
                that.doDelete(taskItem)
              }
            }
          })
        } else {
          let bingKnowledge = ""
          bindingKnowledgeArray.forEach(item => {
            bingKnowledge += ("【" + item.knowledgeLibName + " / " + item.knowledgeName + "】")
          })
          this.$confirm("本知识绑定了" + bindingKnowledgeArray.length + "条知识：" + bingKnowledge + "，删除后该知识也会从绑定知识的相应字段删除且不可恢复，是否确认删除？", "删除警告", {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.doDelete(taskItem)
          })
        }
      })
    },
    doDelete(taskItem) {
      // 如果子任务id为空, 则说明数据库不存在, 无需同步数据库
      if (!taskItem.id) {
        this.$emit("deleteTaskItem", taskItem)
        return
      }
      let param = new URLSearchParams();
      param.append("taskItem", JSON.stringify(taskItem))
      this.axios.post('/pmph/action/task/deleteTaskItemById', param)
        .then(() => {
          this.$emit("deleteTaskItem", taskItem)
        })
    },
    getStatusName(scope) {
      return CONST.TASK_ITEM_STATUS.find(item => item.value === scope.row.status) && CONST.TASK_ITEM_STATUS.find(item => item.value === scope.row.status).key
    },
    getEditorName(scope) {
      return this.editorList.find(item => item.userName === scope.row.editor) && this.editorList.find(item => item.userName === scope.row.editor).name
    },
    getFirstAuditorName(scope) {
      return this.auditorList.find(item => item.userName === scope.row.firstAuditor) && this.auditorList.find(item => item.userName === scope.row.firstAuditor).name
    },
    getSecondAuditorName(scope) {
      return this.auditorList.find(item => item.userName === scope.row.secondAuditor) && this.auditorList.find(item => item.userName === scope.row.secondAuditor).name
    },
    getThirdAuditorName(scope) {
      return this.auditorList.find(item => item.userName === scope.row.thirdAuditor) && this.auditorList.find(item => item.userName === scope.row.thirdAuditor).name
    },
    pressTaskItem(id) {
      this.$confirm('确定催办该任务？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.get("/pmph/action/task/press", {
          params: {
            id: id,
            type: "single"
          }
        }).then(() => {
          this.updatePage()
        })
      })
    },
    detailById: function (id, status) {
      if ('' === id) {
        this.$message({
          message: '该子任务还未建对应的知识',
          type: 'warning'
        });
        return;
      }
      this.knowledgeId = id;
      this.knowledgeStatus = (status === 8 ? 'published' : 'unpublished');
      if (this.systemType === 'knowledge') {
        this.$store.commit('setKnowledgeDetailId', this.knowledgeId)
        this.$store.commit('setKnowledgeDetailStatus', this.knowledgeStatus)
        this.$store.commit('showKnowledgeDetail')
      } else if (this.systemType === 'calc') {
        let url = ''
        if (status !== 8) {
          url = '/pmph/action/medicalCalculator/selectDataById'
        } else {
          url = '/pmph/action/medicalCalculator/selectReleasedCalculatorById'
        }
        let that = this
        this.axios.get(url, {
          params: {
            id: id,
          }
        }).then((response) => {
          that.medicalCalculatorData = response.data.medicalCalculatorData
          that.calculatorSore = response.data.calculatorSore
          that.describeContent = response.data.describeContent
          if (!this.describeContent) {
            this.describeContent = '无'
          }
          that.fields = response.data.fields
          for (let i = 0; i < that.fields.length; i++) {
            if (that.fields[i].kind === 1) {
              that.fields[i].property = JSON.parse(that.fields[i].property)
            }
          }
          that.cntFormulaType = response.data.type
          that.previewDialogVisible = true
        }).catch((error) => {
          console.error(error)
          this.$message.error("获取计算器数据失败");
        });
      } else if (this.systemType === 'flowchart') {
        let routeUrl = this.$router.resolve({
          path: "/flowchart/mobileViewFlowChart",
          query: {
            id: id,
            status: this.knowledgeStatus
          },
        });
        window.open(routeUrl.href, "_blank");
      }
    },
    handleSizeChange(value) {
      this.pageSize = value
    },
  },
  created() {
    this.tableHeight = this.height - 100
  },
  watch: {
    height(value) {
      this.tableHeight = this.height - 100
    }
  }
}
</script>

<style scoped>
#taskItemTable /deep/ .el-table__body-wrapper {
  height: calc(100% - 50px) !important;
}
</style>
